package com.example.demo.java8.stream.parallel;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.stream.IntStream;

/**
 * ForkJoinTask
 *
 *  ForkJoinPool 主要使用分治法（Divide-and-Conquer Algorithm）来解决问题。
 *  根据名称我们可以将其分为 Fork 和 Join 两个阶段。典型的应用比如快速排序算法
 *
 * @author Roger
 * @since 2021/7/18
 */
public class CountTaskTest extends RecursiveTask<Integer> {
    private static final int THRESHOLD = 2;
    private int start;
    private int end;

    public CountTaskTest(int start, int end) {
        this.start = start;
        this.end = end;
    }

    //实现compute 方法来实现任务切分和计算
    protected Integer compute() {
        int sum = 0;
        boolean canCompute = (end - start) <= THRESHOLD;
        if (canCompute) {
            for (int i = start; i <= end; i++)
                sum += i;
        } else {
            //如果任务大于阀值，就分裂成两个子任务计算
            int mid = (start + end) / 2;
            CountTaskTest leftTask = new CountTaskTest(start, mid);
            CountTaskTest rightTask = new CountTaskTest(mid + 1, end);

            //执行子任务
            leftTask.fork();
            rightTask.fork();

            //等待子任务执行完，并得到结果
            int leftResult = (int) leftTask.join();
            int rightResult = (int) rightTask.join();

            sum = leftResult + rightResult;
        }

        return sum;
    }

    public static void main(String[] args) {
        //使用ForkJoinPool来执行任务
        ForkJoinPool forkJoinPool = new ForkJoinPool();

        //生成一个计算资格，负责计算1+2+3+4
        CountTaskTest task = new CountTaskTest(1, 4000);

        Integer r = forkJoinPool.invoke(task);
        System.out.println(r);
        //  或者可以这样写
        //        Future<Integer> result = forkJoinPool.submit(task);
        //        try {
        //            System.out.println(result.get());
        //        } catch (Exception e) {
        //        }
        //java8 ParallelStreams
        int num = IntStream.rangeClosed(1, 4000).parallel().sum();
        System.out.println("计算的总数为"+num);
    }
}

